﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace AutoExecuteSp
{
    public class ScriptProcessor
    {
        public ExecuteResult ExeCommand(FileInfo sqlFile)
        {
            string str = ConfigReader.GetValue<string>("UID");
            string str2 = ConfigReader.GetValue<string>("PWD");
            string str3 = ConfigReader.GetValue<string>("Server");
            string str4 = ConfigReader.GetValue<string>("DataBase");
            string str6 = string.Format("-S   {0}   -i   \"{1}\"   -U   {2}   -P   {3}  -d {4}", new object[] { str3, sqlFile.FullName, str, str2, str4 });

            var executeResult = new ExecuteResult
            {
                FileInfo = sqlFile
            };

            try
            {
                using (var process = new ScriptProcess
                {
                    StartInfo =
                    {
                        FileName = "sqlcmd.exe",
                        UseShellExecute = false,
                        RedirectStandardInput = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = false,
                        CreateNoWindow = true,
                        Arguments = str6,
                        StandardOutputEncoding = Encoding.UTF8
                    }
                })
                {
                    //process.OutputDataReceived += Process_OutputDataReceived;
                    //process.ErrorDataReceived += Process_OutputDataReceived;
                    process.Start();
                    //process.BeginOutputReadLine();
                    //process.BeginErrorReadLine();
                    executeResult.Message = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();
                    process.Close();
                }
            }
            catch (Exception exception)
            {
                executeResult.Exception = exception;
            }
            return executeResult;
        }
    }
}
